<!-- 生产管理 生产配置 -->
<template>
  <basic-container class="production-page">
    <avue-tabs :option="tabOption" @change="handleChange" style="margin: 0 10px"></avue-tabs>
    <span v-if="tabType.prop === 'productionLineConfig'">
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :defaults.sync="defaults"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="menuRight">
          <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
        </template>
        <template slot-scope="{ type, size, row }" slot="menu">
          <el-button icon="el-icon-document" :size="size" :type="type" v-if="permission.productionline_stationDetail" @click="stationDetails(row.id)">工位详情</el-button>
        </template>
        <template slot="menuLeft">
          <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
        </template>
      </avue-crud>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
      <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    </span>
    <span v-else-if="tabType.prop === 'workStationConfig'">
      <WorkStation />
    </span>
    <export-comp ref="exportComp" page-api-url="mes-product/productionline/page" :option="option" :page="page" :query="query" file-name="产线配置"> </export-comp>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import WorkStation from './station.vue';

import { getList, getDetail, add, update, remove } from '@/api/product/productionline';
import { getList as getWorkshopList } from '@/api/admin/workshop';
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    CommonModalTemplate,
    GlobalModalTemplate,
    WorkStation,
    userTableConfig,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PRODUCTION_LINE',
      visibile: false,
      form: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      workshopList: [],
      // 产线配置页 crud
      option: {
        height: 'calc(100vh - 413px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewTitle: '详情',
        viewBtnText: '详情',
        // excelBtn: true, // 导出
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 150,
        menuWidth: 300,
        columnBtn: false,
        // label: '基础信息',
        // icon: 'el-icon-vertical-bar',
        // arrow: false,
        column: [
          {
            label: '产线名称',
            prop: 'name',
            search: true,
            order: 2,
            searchOrder: 2,
            rules: [
              {
                required: true,
                message: '请输入产线名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产线编码',
            prop: 'code',
            maxlength: 20,
            showWordLimit: true,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入产线编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '车间名称',
            prop: 'workshopId',
            type: 'select',
            search: true,
            order: 3,
            searchOrder: 1,
            popperClass: 'workshop-select',
            hide: true,
            rules: [
              {
                required: true,
                message: '请选择车间名称',
                trigger: 'change'
              }
            ],
            dicData: []
          },
          {
            label: '所属车间',
            prop: 'workshopName'
          },
          {
            label: '产线状态',
            prop: 'status',
            disabled: true,
            order: 4,
            dataType: 'string',
            type: 'select',
            dicData: [
              {
                label: '待产',
                value: '1'
              },
              {
                label: '生产',
                value: '2'
              },
              {
                label: '停线',
                value: '3'
              }
            ],
            addDisplay: false
          },
          {
            label: '负责人',
            prop: 'principalName',
            order: 7,
            disabled: true,
            type: 'search',
            span: 12,
            appendClick: () => {
              this.openUserCommonModal({
                type: 'principalName'
              });
            }
          },
          {
            label: '每天可生产时长',
            prop: 'workingHour',
            order: 8,
            type: 'number',
            span: 12
          },
          {
            label: '创建时间',
            prop: 'createTime',
            disabled: true,
            order: 9,
            span: 12,
            addDisplay: false
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            maxRows: 3,
            minRows: 3,
            maxlength: 300,
            showWordLimit: true
          }
        ]
      },
      data: [],
      tabType: {},
      tabOption: {
        column: [
          {
            label: '产线配置',
            prop: 'productionLineConfig'
          },
          {
            label: '工位配置',
            prop: 'workStationConfig'
          }
        ]
      },
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {} //公用模态框配置信息
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.productionline_add, false),
        viewBtn: this.vaildData(this.permission.productionline_view, false),
        delBtn: this.vaildData(this.permission.productionline_delete, false),
        editBtn: this.vaildData(this.permission.productionline_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  async mounted() {
    this.tabType = this.tabOption.column[0];
    this.$nextTick(() => {
      this.$structuralSplit(this.tabType.label);
    });
    let data = await getWorkshopList(1, 1000);
    this.workshopList = data.data.data.records.map((item) => {
      return {
        label: item.name,
        value: item.id,
        code: item.code
      };
    });
    let findIndex = this.option.column.findIndex((item) => item.prop === 'workshopId');
    if (findIndex > -1) {
      this.option.column[findIndex].dicData = this.workshopList;
    }
  },
  watch: {
    'tabType.label': {
      handler(val) {
        this.$nextTick(() => {
          this.$structuralSplit(val);
        });
      }
    }
  },
  methods: {
    rowSave(row, done, loading) {
      let workshopId = row.workshopId;
      let find = this.workshopList.find((item) => item.value === workshopId);
      row.workshopName = find.label;
      row.workshopCode = find.code;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '添加产线成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '编辑产线成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    beforeOpen(done, type) {
      this.defaults.workshopName.display = false;
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 工位详情
    stationDetails(lineId) {
      this.openLocationCommonModal(lineId);
    },
    openLocationCommonModal(lineId) {
      this.modalName = 'locationModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '工位详情',
        url: '/api/mes-product/product/line/query/station/list/by/lineId',
        isPage: true,
        refreshBtn: false,
        index: false,
        method: 'get',
        query: {
          id: lineId
        },
        align: 'center',
        rowSelectionType: 'single',
        showDetails: false,
        addBtn: false,
        subTitle: {
          show: true,
          name: '工位信息',
          icon: 'el-icon-vertical-bar'
        },
        columnDefs: [
          {
            label: '工位名称',
            prop: 'name',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '工位编码',
            prop: 'code',
            searchLabelWidth: 150,
            searchSpan: 8
          }
        ]
      };
    },
    handleChange(column) {
      this.tabType = column;
      this.$nextTick(() => {
        this.$structuralSplit(this.tabType.label);
      });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        case 'principalName':
          this.modalName = 'principalNameModel';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择负责人（双击进行选择）',
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'USER'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principalNameModel':
          this.form.principalName = this._get(rowData, 'realName', '');
          this.form.principalBy = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scope>
.production-page .avue-group__header {
  display: none;
}
</style>
